package sg.edu.nus.iss.billing.gui;

//Author: Tan Pic Cheng

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;

import sg.edu.nus.iss.billing.controller.CustomerController;
import sg.edu.nus.iss.billing.entity.Address;
import sg.edu.nus.iss.billing.entity.Customer;
import sg.edu.nus.iss.billing.entity.RecordState;
import sg.edu.nus.iss.billing.exception.ControllerException;
import sg.edu.nus.iss.billing.exception.ValidationException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.gui.component.ValidateJTextField;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;
import sg.edu.nus.iss.billing.validation.ValidationRule;

public class AddCustomerPanel extends DefaultFunctionPanel {

	private static final long serialVersionUID = 1L;

	private static int HEIGHT = 30;

	private JLabel lblWarning = new JLabel();;
	private JLabel lblCustHeader;
	private JLabel lblCustNRIC;
	private JLabel lblCustDetails;

	private ValidateJTextField fieldCustNRIC;
	private String fieldCustNRICUpper;

	private JButton lookupButton;
	private JButton restoreButton;
	private JPanel tabPanel;
	private JPanel p;
	private JPanel restorePanel;
	private JTabbedPane tabbedPane;
	private JPanel custInfoPanel;
	private JPanel mobilePlanPanel;
	private JPanel digitalPlanPanel;
	private JPanel cablePlanPanel;
	private JPanel searchPanel;

	// 4 panels to add customer's personal information
	private CustomerFieldPanel custPanel;
	private CustomerAddressPanel custAdd;
	private CustomerContactPanel custContact;
	private CustomerMiscPanel custMisc;

	private CustomerController customerController;
	private Customer cust;

	public void storeData() {

	}

	public String getFieldCustNRIC() {
		return fieldCustNRICUpper;
	}

	public void setFieldCustNRIC(ValidateJTextField fieldCustNRIC) {
		this.fieldCustNRIC = fieldCustNRIC;
	}

	public AddCustomerPanel() {
		customerController = new CustomerController();
		cust = SessionContext.getCustomer();
		if (cust != null && cust.getActive() == RecordState.ACTIVE) {
			super.init("TOPONLY");
		} else
			JOptionPane
					.showMessageDialog(
							null,
							MessageKeyManager
									.getMessage("msg.addCustomerNotification"),
							MessageKeyManager
									.getMessage("msg.addCustomerNotificationTitle"),
							JOptionPane.INFORMATION_MESSAGE);
		super.init("TOPONLY");
	}

	public JPanel createTopPanel() {
		// Specify the top panel to display only NRIC search option
		searchPanel = new JPanel(null);

		lblCustHeader = new JLabel(
				MessageKeyManager.getMessage("label.custHeader"));
		Font f = new Font("Arial", Font.BOLD, 12);
		lblCustHeader.setFont(f);
		lblCustHeader.setBounds(10, 15, 200, HEIGHT);
		searchPanel.add(lblCustHeader);

		JPanel displayOptions = displaySearchOptions();
		displayOptions.setBounds(0, 25, 800, 80);
		searchPanel.add(displayOptions);

		return searchPanel;

	}

	private JPanel displaySearchOptions() {
		// TODO Auto-generated method stub
		JPanel p = new JPanel(null);
		p.setPreferredSize(new Dimension(800, 80));

		lblCustDetails = new JLabel(
				MessageKeyManager.getMessage("label.custDetails"));
		lblCustDetails.setBounds(10, 15, 150, HEIGHT);
		p.add(lblCustDetails);

		lblCustNRIC = new JLabel(MessageKeyManager.getMessage("label.nric"));
		lblCustNRIC.setBounds(10, 40, 200, HEIGHT);
		lblCustNRIC.setVerticalTextPosition(SwingConstants.BOTTOM);
		p.add(lblCustNRIC);

		fieldCustNRIC = new ValidateJTextField(
				MessageKeyManager.getMessage("label.nric"));
		fieldCustNRIC.setBounds(220, 40, 250, 25);
		p.add(fieldCustNRIC);

		lookupButton = new JButton(
				MessageKeyManager.getMessage("button.lookup"));
		lookupButton.setBounds(490, 40, 100, 25);
		lookupButton.addActionListener(new LookupListener());
		p.add(lookupButton);

		return p;
	}

	public JPanel createBottomPanel() {
		tabPanel = new JPanel();

		// Create the tab pages
		// createMobilePlanPanel();
		// createDigitalPlanPanel();
		// create CablePlanPanel();
		// Create a tabbed pane
		tabbedPane = new JTabbedPane();
		tabbedPane.setPreferredSize(new Dimension(800, 600));
		custInfoPanel = createCustomerInfoPanel();
		tabbedPane.addTab(
				MessageKeyManager.getMessage("label.customerInfoPanel"),
				custInfoPanel);
		// tabbedPane.addTab( "Mobile Voice Plan ", mobilePlanPanel );
		// tabbedPane.addTab( "Digital Voice Plan", digitalPlanPanel );
		// tabbedPane.addTab( "Cable Plan", cablePlanPanel );
		tabPanel.add(tabbedPane);

		return tabPanel;
	}

	public JPanel createCustomerInfoPanel() {
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new GridLayout(0, 2));

		custPanel = new CustomerFieldPanel(this);
		custAdd = new CustomerAddressPanel();
		custContact = new CustomerContactPanel();
		custMisc = new CustomerMiscPanel();

		mainPanel.add(custPanel);
		mainPanel.add(custAdd);
		mainPanel.add(custContact);
		mainPanel.add(custMisc);

		return mainPanel;
	}

	private Customer tryStorage() throws ValidationException {
		Customer customerObj = null;
		try {
			String salutation = custPanel.getSaluation().getSelectedItem();
			/* Account ID is using String */

			String custAccID = custPanel.getStringCustID();
			String name = custPanel.getFieldName().getValidatedText();
			String email = custPanel.getFieldEmail().getValidatedText();
			String add1 = custAdd.getFieldAdd1().getValidatedText();
			String add2 = custAdd.getFieldAdd2().getValidatedText();
			String unit = custAdd.getFieldUnit().getValidatedText();
			String postal = custAdd.getFieldPostal().getValidatedText();
			//int postalCode = Integer.parseInt(postal);
			String homeNo = custContact.getFieldHome().getValidatedText();
			String mobileNo = custContact.getFieldMobile().getValidatedText();
			String officeNo = custContact.getFieldOffice().getValidatedText();
			String interests = custMisc.getFieldInterests().getValidatedText();

			customerObj = new Customer();
			Address billing = new Address(add1, add2, unit, postal);
			customerObj.setActive(RecordState.ACTIVE);
			customerObj.setSalutation(salutation);
			customerObj.setAccountNumber(custAccID);
			customerObj.setNRIC(fieldCustNRICUpper);
			customerObj.setName(name);
			customerObj.setEmail(email);
			customerObj.setContactNumber1(homeNo);
			customerObj.setContactNumber2(mobileNo);
			customerObj.setContactNumber3(officeNo);
			customerObj.setBillingAddress(billing);
			customerObj.setInterests(interests);
			/*
			 * ID is the system value and will handle by Dayong only, so do not
			 * need to set in GUI
			 */
			// customerObj.setId(custID);
		} catch (ValidationException ex) {
			throw ex;
		}
		return customerObj;
	}

	public Customer loadCustomer(String nric) {

		Customer custObj = null;

		try {
			custObj = customerController.isNRICExist(nric);

		} catch (ControllerException ex) {
			ErrorDialog.showControllerErrorMessageDialog(ex);
		}

		return custObj;

	}

	public JPanel createActionButtonsPanel() {

		p = new JPanel();
		p.setLayout(new FlowLayout());

		JButton addButton = new JButton(
				MessageKeyManager.getMessage("button.add"));
		addButton.addActionListener(new AddActionListener());

		JButton resetButton = new JButton(
				MessageKeyManager.getMessage("button.reset"));
		resetButton.addActionListener(new ResetListener());

		p.add(addButton);
		p.add(resetButton);

		return p;

	}

	private class ResetListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			custPanel.getFieldName().setText("");
			custPanel.getFieldEmail().setText("");
			custAdd.getFieldAdd1().setText("");
			custAdd.getFieldAdd2().setText("");
			custAdd.getFieldUnit().setText("");
			custAdd.getFieldPostal().setText("");
			custContact.getFieldHome().setText("");
			custContact.getFieldMobile().setText("");
			custContact.getFieldOffice().setText("");
			custMisc.getFieldInterests().setText("");
		}
	}

	private class AddActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				Customer custObj = tryStorage();
				String accountNumber = custPanel.getStringCustID();
				customerController.addCustomer(accountNumber, custObj);
				JOptionPane.showMessageDialog(null, MessageKeyManager.getMessage("msg.addCustomerSuccess"),	MessageKeyManager
								.getMessage("msg.addCustomerSuccessTitle"),
						JOptionPane.INFORMATION_MESSAGE);
				SessionContext.setCustomer(custObj);
				tabPanel.removeAll();
				p.removeAll();
				tabPanel.updateUI();
				p.updateUI();
				new ResetListener().actionPerformed(null);
			} catch (ValidationException ex) {
				ErrorDialog.showValidationErrorMessageDialog(ex);
			} catch (ControllerException ex) {
				ErrorDialog.showControllerErrorMessageDialog(ex);
			} catch (Exception ex) {
				ErrorDialog.showUnhandledErrorMessageDialog(ex);
			}
		}
	}

	public JPanel restoreCustomer() {
		restorePanel = new JPanel();

		restoreButton = new JButton(
				MessageKeyManager.getMessage("button.restore"));
		restorePanel.add("CENTER", restoreButton);

		ActionListener restore = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cust.setActive(RecordState.ACTIVE);
				try {
					customerController.editCustomer(cust);
				} catch (ControllerException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				searchPanel.remove(lblWarning);
				searchPanel.updateUI();
				String msg = MessageKeyManager.getMessage(
						"msg.addCustomerRestore", fieldCustNRICUpper);
				lblWarning.setText(msg);
				searchPanel.add("CENTER", lblWarning);
				searchPanel.updateUI();
				restorePanel.setVisible(false);
			}
		};

		restoreButton.addActionListener(restore);

		return restorePanel;
	}

	public class LookupListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {

			try {
				if (tabPanel != null) {
					tabPanel.removeAll();
					tabPanel.updateUI();
				}
				if (p != null) {
					p.removeAll();
					p.updateUI();
				}
				if (lblWarning.isShowing() == true) {
					searchPanel.remove(lblWarning);
					searchPanel.updateUI();
				}
				fieldCustNRICUpper = fieldCustNRIC.getText().toUpperCase().trim();
				fieldCustNRIC.setText(fieldCustNRICUpper);
				fieldCustNRIC.setRules(ValidationRule.NOT_NULL,
						ValidationRule.NRIC);
				cust = loadCustomer(fieldCustNRIC.getValidatedText());
				if (cust != null && cust.getActive() == RecordState.ACTIVE) {
					String msg = MessageKeyManager.getMessage("msg.addCustomerExistingRecord",fieldCustNRIC.getText());
					lblWarning.setText(msg);
					lblWarning.setBounds(180, 100, 350, 20);
					searchPanel.add(lblWarning);
					searchPanel.updateUI();
				} else if (cust != null	&& cust.getActive() == RecordState.DELETED) {
					SessionContext.setCustomer(cust);
					if (restorePanel != null)
						restorePanel.setVisible(true);
					String msg = MessageKeyManager.getMessage(
							"msg.addCustomerDeleteByNRIC",
							fieldCustNRIC.getText());
					lblWarning.setText(msg);
					lblWarning.setBounds(180, 100, 400, 20);
					lblWarning.setVerticalTextPosition(SwingConstants.BOTTOM);
					searchPanel.add(lblWarning);
					searchPanel.updateUI();
					refreshBottomPanel(restoreCustomer());
				} else {
					SessionContext.setCustomer(cust);
					refreshBottomPanel(createBottomPanel());
					refreshActionButtonPanel(createActionButtonsPanel());
				}
				fieldCustNRIC.setText("");
			} catch (ValidationException ex) {
				ErrorDialog.showValidationErrorMessageDialog(ex);
			}

		}
	}
}
